<template>
  <div class="test-case-management">
    <h1>测试用例管理</h1>
    <div class="test-case-list">
      <!-- 新增测试用例按钮 -->
      <button @click="doAdd" class="add-button">新增测试用例</button>
      <el-button type="primary" @click="selectFolder">📁 选择文件夹</el-button>
      <input type="file" ref="folderInput" webkitdirectory multiple @change="handleFolderChange" style="display: none">
      <!-- 测试用例列表 -->
      <div v-for="testCase in testCases" :key="testCase.id" class="test-case">
        <span>{{ testCase.name }}</span>
        <div>
          <button @click="toEditName(testCase)">修改名称</button>
          <button @click="doEdit(testCase)">编辑内容</button>
          <button @click="doExport(testCase)">导出实例</button>
          <button @click="confirmDeleteTestCase(testCase)" class="delete-button">删除</button>
        </div>
      </div>
    </div>
    <el-dialog
      title="修改测试用例名称"
      v-model="editDialogVisible"
      @@before-leave="resetForm"
      width="30%">
      <el-form>
        <el-form-item label="测试用例名称">
          <el-input v-model="form.name" placeholder="请输入测试用例名称"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="editDialogVisible = false" type="danger">取 消</el-button>
        <el-button type="primary" @click="doEditName" >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { apiAddTestcase, apiListTestcase, apiDelTestcase, apiUploadTestcase, apiEditTestcaseHeader, apiInfoTestcase } from '@/api/testcase';
import { ElMessage } from 'element-plus';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import JSZip from "jszip";
import { id } from 'element-plus/es/locale/index.mjs';

const router = useRouter();
const  editDialogVisible = ref(false);
const form  = ref({
  id: 0,
  name: ''
});

const resetForm = () => {
  form.value = {
    id: 0,
    name: ''
  };
};

const testCases = ref([]);
const folderInput = ref();
const selectFolder = () => {
  folderInput.value.click();
};

const doEdit = (row) => {
  // 跳转到测试步骤编辑页面，并传递测试用例 ID
  router.push({ name: 'TestStepEditorPage', query: { filename: row.id } });
};

const confirmDeleteTestCase = (row) => {
  // 确认删除测试用例
  if (confirm('确定要删除该测试用例吗？')) {
    doDel(row);
  }
};

const toEditName  = (row) => {
  form.value.id = row.id;
  form.value.name = row.name;
  editDialogVisible.value = true;
}

const doEditName = async() => {
  const res = await apiEditTestcaseHeader({id: form.value.id, name: form.value.name})
  if (!res || res.code !== 200) {
    ElMessage.error('修改测试用例名称失败')
    return
  }
  editDialogVisible.value = false
  getList()
};

const doExport = async(val) => {
  const res = await apiInfoTestcase(val.id)
  const blob = new Blob([res]);
  const url = window.URL.createObjectURL(blob);

  // 创建 a 标签并下载
  const a = document.createElement("a");
  a.href = url;
  a.download = "实例.zip"; // 设置下载文件名
  document.body.appendChild(a);
  a.click();

  // 清理
  window.URL.revokeObjectURL(url);
  document.body.removeChild(a);
}

const handleFolderChange = (event) => {
  zipAndUpload(Array.from(event.target.files))
};

const zipAndUpload = async (fileList) => {
  if (!fileList.length) {
    alert("请先选择文件夹！");
    return;
  }

  const zip = new JSZip();
  fileList.forEach((file) => {
    zip.file(file.webkitRelativePath, file);
  });

  try {
    const zipBlob = await zip.generateAsync({ type: "blob" });
    const formData = new FormData();
    formData.append("file", zipBlob, `${Date.now()}.zip`);

    // 发送 POST 请求上传
    await apiUploadTestcase(formData);
    getList()
  } catch (error) {
    console.error("ZIP 处理或上传失败:", error);
  }
};

const doDel = async(row) => {
  const res = await apiDelTestcase(row.id)
  if (!res || res.code !== 200) {
    ElMessage.error('删除测试用例失败')
    testCases.value = []
    return
  }
  getList()
};

const doAdd = async() => {
  const res = await apiAddTestcase()
  if (!res || res.code !== 200) {
    ElMessage.error('新增测试用例失败')
    return
  }
  getList()
};

const getList = async() => {
  const res = await apiListTestcase()
  if (!res || res.code !== 200) {
    ElMessage.error('获取测试用例列表失败')
    testCases.value = []
    return
  }
  testCases.value = res.data.list
};


onMounted(() => {
  getList()
});
</script>

<style scoped>
.test-case-management {
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

h1 {
  text-align: center;
  color: #4a4a4a;
}

.test-case-list {
  margin-top: 20px;
}

.test-case {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

button {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  background-color: #409eff;
  color: #fff;
  cursor: pointer;
  margin-left: 8px;
}

button:hover {
  background-color: #337ecc;
}

.delete-button {
  background-color: #ff4d4f;
}

.delete-button:hover {
  background-color: #d9363e;
}

.add-button {
  background-color: #67c23a;
  margin-bottom: 20px;
}

.add-button:hover {
  background-color: #5daf34;
}

.dialog-footer{
  display: flex;
  width: 100%;
  justify-content: flex-end;
}
</style>